package com.laxcen.basiclib.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import com.laxcen.basiclib.BaseApp;
import com.laxcen.basiclib.core.broadcast.BroadcastManager;
import com.laxcen.basiclib.core.mqtt.MqttManager;
import com.laxcen.basiclib.utils.CommonUtil;
import com.laxcen.basiclib.utils.LogUtil;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.HashMap;
import java.util.Map;


/**
 *  MQTT 的服务
 */
public class MqttService extends Service {

    private static boolean hasStart = false;

    //系统默认topic
    public static String[] topics = {
            "/app/updateVersion",//版本更新推送
            "test",
            "app"
    };

    //启动
    public static void actionStart(Context context){
        if(hasStart){
            return;
        }
        hasStart = true;
        if(CommonUtil.isServiceRunning(context, MqttService.class)){
            return;
        }
        Intent intent = new Intent(context, MqttService.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startService(intent);
    }

    //结束
    public static void actionStop(Context context){
        Intent intent = new Intent(context, MqttService.class);
        context.stopService(intent);
    }

    private BroadcastManager broadcastManager;
    private static String MQTT_MESSAGE_PUBLISH = "MQTT_MESSAGE_PUBLISH";
    public static String MQTT_MESSAGE_LISTENER = "MQTT_MESSAGE_LISTENER";
    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        broadcastManager.unregister(MQTT_MESSAGE_PUBLISH);
        broadcastManager.unregister(MQTT_MESSAGE_LISTENER);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return  null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.i("mqtt.onStartCommand");
        try {
            if(mqttManager==null) {
                initMqtt();
            }
        }catch (Exception e){
            LogUtil.e("MqttService.onStartCommand",e.getMessage());
        }
        return START_STICKY;
    }

    private MqttManager mqttManager;
    private void initMqtt(){

        broadcastManager = BroadcastManager.getInstance(this);
        broadcastManager.register(MQTT_MESSAGE_PUBLISH, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                String type = intent.getStringExtra("type");
                LogUtil.d("MQTT_MESSAGE_PUBLISH","type->",type);
                switch (type){
                    case "publish":
                        String topic = intent.getStringExtra("topic");
                        String message = intent.getStringExtra("message");
                        if(mqttManager!=null){
                            mqttManager.publish(topic,message);
                        }
                        break;
                    case "subscribe":
                        String topic1 = intent.getStringExtra("topic");
                        if(mqttManager!=null){
                            mqttManager.subscribe(topic1);
                        }
                        break;
                    case "unsubscribe":
                        String topic2 = intent.getStringExtra("topic");
                        if(mqttManager!=null){
                            mqttManager.unsubscribe(topic2);
                        }
                        break;
                }
            }
        });

        mqttManager = MqttManager.getInstance();
        mqttManager.setMqttMessageCallback(new MqttManager.MqttMessageCallback() {
            @Override
            public void onMessageArrived(String topic, MqttMessage mqttMessage) {
                String msg = new String(mqttMessage.getPayload());
                LogUtil.d("MqttManager.onMessageArrived",topic,msg);
                //广播通知到其他地方
                Map<String,Object> map = new HashMap<>();
                map.put("type",MqttManager.ActionType.ON_RECEIVER.name());
                map.put("topic",topic);
                map.put("msg",msg);
                BroadcastManager.getInstance(BaseApp.getApp()).sendBroadcast(MQTT_MESSAGE_LISTENER,map);
            }

            @Override
            public void onAction(MqttManager.ActionType type, String msg) {
                LogUtil.d("MqttManager.onAction",type.toString(),msg);
                //系统内部预处理
                switch (type){
                    case  SEND_SUCCESS:

                        break;
                    case CONNECT_FAIL:
                        break;
                    case NO_NETWORK:
                        break;
                    case CONNECT_SUCCESS:
                        subscribeSystemTopic();
                        break;
                    case CONNECT_LOST:
                        break;
                }
                //广播通知到其他地方
                Map<String,Object> map = new HashMap<>();
                map.put("type",type.name());
                map.put("msg",msg);
                BroadcastManager.getInstance(BaseApp.getApp()).sendBroadcast(MQTT_MESSAGE_LISTENER,map);
            }
        });
    }

    /**
     *  订阅系统内置主题
     */
    private void subscribeSystemTopic(){
        for(String topic:topics){
            mqttManager.subscribe(topic);
        }
    }
    /**
     *  发布消息
     * @param topic
     * @param message
     */
    public static void publish(String topic,String message){
        LogUtil.i("mqtt.phlish",topic,message);
        Map<String,Object> map = new HashMap<>();
        map.put("type", "publish");
        map.put("topic", topic);
        map.put("message",message);
        BroadcastManager.getInstance(BaseApp.getApp()).sendBroadcast(MQTT_MESSAGE_PUBLISH,map);
    }

    /**
     *  订阅主题
     * @param topic
     */
    public static void subscribe(String topic){
        LogUtil.i("mqtt.subscribe",topic);
        Map<String,Object> map = new HashMap<>();
        map.put("type","subscribe");
        map.put("topic",topic);
        BroadcastManager.getInstance(BaseApp.getApp()).sendBroadcast(MQTT_MESSAGE_PUBLISH,map);
    }

    /**
     *  取消订阅主题
     * @param topic
     */
    public static void unsubscribe(String topic){
        LogUtil.i("mqtt.unsubscribe",topic);
        Map<String,Object> map = new HashMap<>();
        map.put("type", "unsubscribe");
        map.put("topic", topic);
        BroadcastManager.getInstance(BaseApp.getApp()).sendBroadcast(MQTT_MESSAGE_PUBLISH,map);
    }
}
